package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.workflow.bpmconst.BpmConst;
import com.ccp.dev.workflow.model.ActDefModel;
import com.ccp.dev.workflow.model.BpmNodeScript;
import com.ccp.dev.workflow.model.FlowNodeInfo;
import com.ccp.dev.workflow.model.NodeCache;
import com.ccp.dev.workflow.service.ActDefModelService;
import com.ccp.dev.workflow.service.BpmNodeScriptService;
import com.ccp.dev.workflow.service.BpmService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * ClassDescribe:节点运行脚本控制器类
 * @author :jiayueqiao
 * Date: 2019-07-04
 * Since:1
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT +UrlConstants.PROJECT_MODULE_WORKFLOW+"/bpmNodeScript")
@Action(ownermodel=SysAuditModelType.PROCESS_MANAGEMENT)
public class BpmNodeScriptController extends SysBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BpmNodeScriptController.class);
    @Resource
    private BpmNodeScriptService bpmNodeScriptService;
    @Resource
    private BpmService bpmService;
    @Resource
    private ActDefModelService actDefModelService;

    /**
     * 节点脚本设置
     * @return String
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/edit")
    @Action(description = "查看节点脚本设置页面",detail = "查看节点脚本设置页面")
    public String viewEdit(HttpServletRequest request,Model model) {
        String modelId=RequestUtil.getString(request, "modelId");
        String nodeId=RequestUtil.getString(request, "nodeId");
        String procDefId=RequestUtil.getString(request, "procDefId");
        String type=RequestUtil.getString(request, "type");
        String parentProcDefId = RequestUtil.getString(request, "parentProcDefId");
        Map<String,String> map= bpmNodeScriptService.getMapByNodeIdAndProcDefId(nodeId, procDefId);

        String script = null;
        if (BpmConst.SCRIPT_TASK.equalsIgnoreCase(type)) {
            try {
                script = bpmService.getScriptInModel(nodeId, modelId);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        model.addAttribute("map",map)
                .addAttribute("type", type)
                .addAttribute("nodeId", nodeId)
                .addAttribute("procDefId", procDefId)
                .addAttribute("modelId", modelId)
                .addAttribute("script", script)
                .addAttribute("parentProcDefId", parentProcDefId);
     return getAutoView();
    }


    /**
     * 添加或更新节点运行脚本
     * @param request request
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @Action(description="添加或更新节点运行脚本",
            detail="保存流程定义 【${actDefModel.description}-${actDefModel.modelKey}】" +
                    "的节点 【${nodeName}】的脚本设置（事件设置）<#if fl>成功<#else>失败</#if>"
    )
    @ResponseBody
    public ResultData save(HttpServletRequest request)
    {
        String nodeId=RequestUtil.getString(request, "nodeId");
        String procDefId=RequestUtil.getString(request, "procDefId");

        //2019-11-13 jyq修改，添加日志信息
        FlowNodeInfo flowNode = NodeCache.getNodeByActNodeId(procDefId, nodeId);
        String nodeName = flowNode.getNodeName();
        SysAuditThreadLocalHolder.putParamerter("nodeName", nodeName);
        ActDefModel actDefModel = actDefModelService.getByProcDefId(procDefId);
        SysAuditThreadLocalHolder.putParamerter("actDefModel", actDefModel);

        String[] aryScript=request.getParameterValues("script");
        String[] aryScriptType=request.getParameterValues("scriptType");
        List<BpmNodeScript> list=new ArrayList<>();
        for(int i=0;i<aryScriptType.length;i++){
            String script=aryScript[i];
            Integer type=Integer.parseInt(aryScriptType[i]);
            if(StringUtil.isEmpty(script)){
                continue;
            }
            BpmNodeScript bpmNodeScript=new BpmNodeScript();
            bpmNodeScript.setScript(script);
            bpmNodeScript.setScriptType(type);
            list.add(bpmNodeScript);

        }
        try{
            bpmNodeScriptService.saveScriptDef(procDefId, nodeId, list);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("script.save.success");
        } catch ( Exception e) {
            LOGGER.debug(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("script.save.failure");
        }
    }

    @RequestMapping("/saveScriptInModel")
    @Action(description="添加脚本节点运行脚本",
            detail="保存流程定义 【${actDefModel.description}-${actDefModel.modelKey}】" +
                    "的脚本节点 【${nodeName}】的脚本<#if fl>成功<#else>失败</#if>"
    )
    @ResponseBody
    public ResultData saveScriptInModel(HttpServletRequest request) {
        String nodeId=RequestUtil.getString(request, "nodeId");
        String procDefId=RequestUtil.getString(request, "procDefId");
        String script=RequestUtil.getString(request, "script");

        //2019-11-13 jyq修改，添加日志信息
        FlowNodeInfo flowNode = NodeCache.getNodeByActNodeId(procDefId, nodeId);
        String nodeName = flowNode.getNodeName();
        SysAuditThreadLocalHolder.putParamerter("nodeName", nodeName);
        ActDefModel actDefModel = actDefModelService.getByProcDefId(procDefId);
        SysAuditThreadLocalHolder.putParamerter("actDefModel", actDefModel);

        try {
            bpmService.saveScriptInModel(nodeId,procDefId, script);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("script.save.success");
        } catch (Exception e) {
            LOGGER.debug(e.getMessage());
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("script.save.failure",1,e.getMessage());
        }

    }
}
